package com.test.web.service;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.he.core.ResultT;
import com.he.web.biz.CheckPage;
import com.test.web.bean.vue.sort.SortBean;
import com.test.web.dao.RoleDao;
import com.test.web.entity.Role;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author heyanjing
 * date:2020-07-03 2020/7/3:9:57
 */
@Slf4j
@Service
public class RoleService {

    @Resource
    private RoleDao roleDao;

    public ResultT insert(Role role) throws Exception {
        role.setRoleId(IdUtil.simpleUUID());
        role.setIsSuper(false);
        role.setState("valid");
        roleDao.insert(role);
        return ResultT.success();
    }

    public ResultT<Role> get(String roleId) {
        Role role = roleDao.selectByPrimaryKey(roleId);
        return ResultT.successWithData(role);
    }

    public ResultT update(Role role) throws Exception {
        Role existRole = roleDao.selectByPrimaryKey(role.getRoleId());
        CheckPage.set(existRole, role);
        roleDao.updateByPrimaryKeySelective(existRole);
        return ResultT.success();
    }

    public ResultT delete(String roleId) {
        List<String> idList = Arrays.asList(roleId.split(","));
        roleDao.updateStateByRoleIdIn("del", idList);
        return ResultT.success();
    }

    public ResultT<PageInfo<Role>> find(String search, String state, String sort, Integer pageIndex, Integer pageSize) {
        List<SortBean> sortList = new ArrayList<>();
        if (StringUtils.isNotBlank(sort)) {
            List<String> sortStrList = Arrays.asList(sort.split(","));
            for (String sortStr : sortStrList) {
                String[] sortArr = sortStr.split("_");
                sortList.add(new SortBean(sortArr[0], "ascending".equals(sortArr[1]) ? "asc" : "desc"));
            }
        }

        PageHelper.startPage(CheckPage.checkPageIndex(pageIndex), CheckPage.checkPageSize(pageSize));
        List<Role> roleList = roleDao.findByRoleNameLike(search, state, sortList);
        PageInfo<Role> pageInfo = PageInfo.of(roleList);
        return ResultT.successWithData(pageInfo);
    }

}
